﻿token="";
school="";
userId	=	"";
studentId="";
classUser="";
type=""
jsonMarkStudent="";
jsonAttendance="";
function	login()
{
	//	ajax	get	cfrs	token
	$.ajax({
		dataType:	"json",
		url:	"http://truongnha.com/api/login/",
		
		type:	"GET",
		success:	function(data){
			var	myJSONText	=	JSON.stringify(data,	replacer);
			//alert(	"OK:	"	+	myJSONText);
			token=data.csrfmiddlewaretoken;
			//alert("OK");
			//******************
			
			var usern = document.getElementById("username").value;
			var pass = document.getElementById("password").value
			
			
			$.ajax({//	cau	lenh	ajax	POST	vs	usernam	password
				dataType:	"json",
				url:	"http://truongnha.com/api/login/",
				type:	"POST",
				data:	{username:usern,password:pass,csrfmiddlewaretoken:token},
				success:	function(	data){
					var	myJSONText	=	JSON.stringify(data,	replacer);
					token2=	JSON.stringify(data,	replacer);
					//token2=data;
					
					school=data.user.school;
					studentId=data.user.studentId;
					type=data.user.type;
					userId=data.user.userId;
					classUser=data.user.class;
					
					console.log( "School: " + school + "  UserId: " + userId + " Student ID: " + studentId + " classUser: " + classUser + " Type: " + type );
					
					onDeviceReady();
					window.location.assign("screen_detail.html");
				},
				error:	function(xhr,	textStatus,	error){
					alert("Erorr user name or password. Try again");
					document.getElementById("username").value="";
					document.getElementById("password").value="";
				}
			});//	end	ajax	submit
			//******************
		},
		error:	function(xhr,	textStatus,	error){
				var	myJSONText	=	JSON.stringify(xhr,	replacer);
				alert(	"Eror get token:	"	+	myJSONText);
		}
	});//	end	ajax	get	token
			
}//	end	funciton	login	to	server


// function singout to app
function signout()
{
	$.ajax({
		url:"http://truongnha.com/api/logout",
		type:"GET",
					
		success: function(data)
		{
		},
		erorr: function()
		{
			alert("Erorr to logout");
		}
		
	});
	window.location.assign("index.html");
}

function logout()
{
	$.ajax({
		url:"http://truongnha.com/api/logout",
		type:"GET",
					
		success: function(data)
		{
			alert("Logout success");
		},
		erorr: function()
		{
			alert("Erorr to logout");
		}
		
	});
}
// function conver object json to string
function replacer(key, value) {
	if (typeof value === 'number' && !isFinite(value)) {
			return String(value);
		}
	return value;
}

/**
*	hien thi thong tin sinh vien khi lay tu api/login
*/

function display()
{
	
}
//-------------------------------------------------------------------------------------
/**
**	// Cac ham xu ly tao co so du lieu
**/
//--------------------------------------------------------------------------------------

function displayDB()
{
	onDeviceReady();
}
//document.addEventListener("deviceready", onDeviceReady, false);

// Populate the database 
//
function populateDB(tx) {
	tx.executeSql('DROP TABLE IF EXISTS DEMO');
	tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, school text,userId text, studentId text,classUser text, type text)');
	console.log( "School: " + school + "  UserId: " + userId + " Student ID: " + studentId + " classUser: " + classUser + " Type: " + type );
	tx.executeSql('INSERT INTO DEMO (id, school,userId,studentId,classUser,type) VALUES (1, "' + school+ '", "'+userId+ '","'+studentId + '","'+classUser+'","'+type+'")');
	
}

// Query the database
//
function queryDB(tx) {
	tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}

// Query the success callback
//
function querySuccess(tx, results) {
	var len = results.rows.length;
	console.log("DEMO table: " + len + " rows found.");
	for (var i=0; i<len; i++){
		console.log("Row = " + i + " ID = " + results.rows.item(i).id + " School =  " + results.rows.item(i).school + 
		" User ID: " + results.rows.item(i).userId + " Student Id = " + results.rows.item(i).studentId + " User class = " 
		+ results.rows.item(i).userId + " Type = " + results.rows.item(i).type);
	}
}

// Transaction error callback
//
function errorCB(err) {
	console.log("Error processing SQL: "+err.code);
}

// Transaction success callback
//
function successCB() {
	var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 2000000);
	db.transaction(queryDB, errorCB);
}

// PhoneGap is ready
//
function onDeviceReady() {
	var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 2000000);
	db.transaction(populateDB, errorCB, successCB);
}
function OK()
{

}
// Display profile user in 
function displayProfileUser()
{
	window.location.assign("profile.html");
}


//---------------------------------------
/**
*	Get json mark, create table MARK STUDENT
**/
// get json mark for student
function getMark()
{
	var urls= "http://truongnha.com/api/markForAStudent/19461";
	//alert(urls);
	$.ajax({// cau lenh ajax POST vs usernam password
	dataType: "json",
	url: urls,
	type: "GET",
	success: function( data){ /* get read data from json to database with nameTable MARKSTUDENT*/
		var	myJSONText	=	JSON.stringify(data,replacer);
		jsonMarkStudent=data;
		//console.log(myJSONText);
		//alert(data[0].mark[0].t);
		startCreateTableMarkStudent();
	},
	error: function(xhr, textStatus, error){
		alert("Erorr mark");
	}
	});// end ajax
}

// create table MARKSTUDENT
function createTableMarkStudent(tx) {
	tx.executeSql('DROP TABLE IF EXISTS MARKSTUDENT');
	tx.executeSql('CREATE TABLE IF NOT EXISTS MARKSTUDENT (id int,isComment text, nameObject text,m text, t DATETIME,n int)');
	
	// loop to read data from jsonObject to create table

	for (var i in jsonMarkStudent){
		for( var j in jsonMarkStudent[i].mark)
		{
			tx.executeSql('INSERT INTO MARKSTUDENT (id, isComment,nameObject,m,t,n) VALUES ('+jsonMarkStudent[i].id+',"'+jsonMarkStudent[i].isComment+'","'+jsonMarkStudent[i].name+
			'","'+jsonMarkStudent[i].mark[j].m+'","'+jsonMarkStudent[i].mark[j].t+'",'+jsonMarkStudent[i].mark[j].n+')');
		}
	}// end for 
	
}// end create table MARKSTUDENT


// 
//
function queryDBMarkStudent(tx) {
	tx.executeSql('SELECT * FROM MARKSTUDENT order by t desc', [], querySuccessMarkStudent, errorCBMarkStudent1);
	
}

// read data from MARKSTUDENT, and set innerHTMK, conntent-tbody
//
function querySuccessMarkStudent(tx, results) {
	var len = results.rows.length;
	console.log("MARKSTUDENT table: " + len + " rows found.");
	var value ;
	for (var i=0; i<len; i++){
	
		value +="<tr><td>" + results.rows.item(i).t + "</td>";
		var kt = results.rows.item(i).n;
		if( kt <= 8 )
			value +="<td>" + "Mouth mark" + "</td>";
		else if(kt <=16)
			value +="<td>" + "15' mark" + "</td>";
		else if(kt<=24)
			value +="<td>" + "Period mark" + "</td>";
		else if(kt==25)
			value +="<td>" + "Final mark" + "</td>";
		else
			value +="<td>" + "Average" + "</td>";
		value +="<td>" + results.rows.item(i).m  + "</td></tr>";
	
		console.log(" ID = " + results.rows.item(i).id + " IsCommnent =  " + results.rows.item(i).idCommnet + 
		" Name Object: " + results.rows.item(i).nameObject + " m = " + results.rows.item(i).m + " n = " 
		+ results.rows.item(i).n + " t = " + results.rows.item(i).t);
		
	}
	document.getElementById("content-tbody").innerHTML=value;
}

// Transaction error callback
//
function errorCBMarkStudent1(err) {
	console.log("Error processing SQL 1: "+err.code);
}
function errorCBMarkStudent2(err) {
	console.log("Error processing SQL 2: "+err.code);
}
// Transaction success callback
//
function successCBMarkStudent() {
	var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 2000000);
	db.transaction(queryDBMarkStudent, errorCBMarkStudent2);
}
function startCreateTableMarkStudent() {
	var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 2000000);
	db.transaction(createTableMarkStudent, errorCBMarkStudent1, successCBMarkStudent);
}
// đọc dữ liệu từ bảng MarkStudent theo môn học nhóm dữ liệu theo môn học


/**
*	Get attendance

**/

function getAttendanceJson()
{
	var urls= "http://truongnha.com/api/getAttendanceForStudent/allYear";
	//alert(urls);
	$.ajax({// cau lenh ajax POST vs usernam password
	dataType: "json",
	url: urls,
	type: "GET",
	success: function( data){ 
		var	myJSONText	=	JSON.stringify(data,replacer);
		jsonAttendance=data;
		console.log(myJSONText);
		//alert(data[0].mark[0].t);
		startCreateTableAttendance();
	},
	error: function(xhr, textStatus, error){
		alert("Erorr get attendance");
	}
	});// end ajax
	
}

// create table ATTENDANCE
function createTableAttendance(tx) {
	tx.executeSql('DROP TABLE IF EXISTS ATTENDANCE');
	tx.executeSql('CREATE TABLE IF NOT EXISTS ATTENDANCE (type text,t text)');
	
	// loop to read data from jsonObject to create table
	
	for (var i in jsonAttendance){
			tx.executeSql('INSERT INTO ATTENDANCE (type, t) VALUES ("'+jsonAttendance[i].type+'","'+jsonAttendance[i].time+'")');
	}// end for 
	
}// end create table ATTENDANCE


// 
//
function queryDBAttendance(tx) {
	tx.executeSql('SELECT * FROM ATTENDANCE', [], querySuccessAttendance, errorCBAttendance1);
	
}

// read data from ATEENDANCE, and set innerHTMK, conntent-tbody
//
function querySuccessAttendance(tx, results) {
	var len = results.rows.length;
	console.log("ATTENDANCE table: " + len + " rows found.");
	var value;
	for (var i=1; i<=len; i++){
		value +="<tr><th>" + i + "</th>";
		value +="<td>" + results.rows.item(i-1).t + "</td>";
		var kt = results.rows.item(i-1).type;
		
		if( kt == "M" ){
			value +="<td>" + "Muộn" + "</td>";
		}
		else if(kt =="P"){
			value +="<td>" + "Có phép" + "</td>";
		}
		else if(kt =="K"){
			value +="<td>" + "Không phép" + "</td>";
		}
		value +="</tr>";
	
		console.log(" type = " + results.rows.item(i-1).type + " time =  " + results.rows.item(i-1).t );
		
	}
	document.getElementById("content-tbody").innerHTML=value;
}

// Transaction error callback
//
function errorCBAttendance1(err) {
	console.log("Error processing SQL 1: "+err.code);
}
function errorCBAttendance2(err) {
	console.log("Error processing SQL 2: "+err.code);
}
// Transaction success callback
//
function successCBAttendance() {
	var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 2000000);
	db.transaction(queryDBAttendance, errorCBAttendance2);
}
function startCreateTableAttendance() {
	var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 2000000);
	db.transaction(createTableAttendance, errorCBAttendance1, successCBAttendance);
}